package com.wellness.commons.encrypt;

import org.apache.commons.codec.binary.Hex;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.*;
import java.util.Arrays;


public class SignatureUtils {

    private static String HMACSHA256(final String data, final String key) {
        String result = null;
        try {
            Mac hmac_sha256 = Mac.getInstance("HmacSHA256");
            SecretKeySpec secret_key = new SecretKeySpec(key.getBytes(),
                    "HmacSHA256");
            hmac_sha256.init(secret_key);
            byte[] hash = hmac_sha256.doFinal(data.getBytes());
            result = Hex.encodeHexString(hash);
            return result;
        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            return result;
        }
    }
    public static String makeSHA256(String s) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            digest.update(s.getBytes());
            byte[] messageDigest = digest.digest();
            return bytesToHexString(messageDigest);
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
    }

    public static String makeSHA512(String s) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-512");
            digest.update(s.getBytes());
            byte[] messageDigest = digest.digest();
            return bytesToHexString(messageDigest);
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
    }

    public static String encryptOfAES(String s,String k) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        if (s == null || k == null) {
            throw new IllegalArgumentException();
        }
        SecretKeySpec key = new SecretKeySpec(k.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");// 创建密码器
        cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
        byte[] result = cipher.doFinal(s.getBytes());// 加密
        return bytesToHexString(result);
    }

    public static String decryptOfAES(String s,String k) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, BadPaddingException, IllegalBlockSizeException {
        if (s == null || k == null) {
            throw new IllegalArgumentException();
        }
        SecretKeySpec key = new SecretKeySpec(k.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");// 创建密码器
        cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
        byte[] result = cipher.doFinal(hexStringToBytes(s)); // 加密
        return new String(result);
    }

    private static Object object = new Object();

    public static String decryptOfAES(byte[] s, byte[] k, byte[] iv) throws Exception {
        synchronized (object) {
            Provider provider = Security.getProvider(BouncyCastleProvider.PROVIDER_NAME);
            if (provider == null) {
                provider = new BouncyCastleProvider();
                Security.addProvider(provider);
                System.out.println("add provider" + provider.getInfo());
            }
        }
        // 如果密钥不足16位，需要补足
        byte[] kBytes = k;
        int base = 16;
        if (kBytes.length % base != 0) {
            int groups = kBytes.length / base + (kBytes.length % base != 0 ? 1 : 0);
            byte[] temp = new byte[groups * base];
            Arrays.fill(temp, (byte) 0);
            System.arraycopy(kBytes, 0, temp, 0, kBytes.length);
            kBytes = temp;
        }
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", BouncyCastleProvider.PROVIDER_NAME);
        Key sKeySpec = new SecretKeySpec(kBytes, "AES");
        AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
        params.init(new IvParameterSpec(iv));
        cipher.init(Cipher.DECRYPT_MODE, sKeySpec, params);
        byte[] result = cipher.doFinal(s);
        return new String(result);
    }

    private static String bytesToHexString(byte[] src){
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }
    /**
     * Convert hex string to byte[]
     * @param hexString the hex string
     * @return byte[]
     */
    private static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }

    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

}
